﻿using System;

namespace CustomerContactSystem.WebForms.Enquiries.Referrals {
    public partial class CreateNewDepartment : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id,dept")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
            GetCategories();
        }

        private void GetCategories() {
            var departmentId = int.Parse(Request.QueryString["dept"]);
            var categories = EnquiryCategoryRepository.QueryOver()
                .Where(c => c.AvailableForSelection && c.Department.Id == departmentId)
                .OrderBy(c => c.CategoryName).Asc.List();
            BindDropDownList(Categories, categories, "CategoryName", "Id", "--Select--", "0");
        }

        protected void UpdateEnquiryClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            var categoryId = int.Parse(Categories.SelectedItem.Value);
            var category = EnquiryCategoryRepository.GetById(categoryId);

            if (category == null) {
                UpdateEnquiryResultMessage.Text = "Please select a category!";
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);
            
            enquiry.ChangeCategory(category);

            EnquiryRepository.Update(enquiry);
            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }
    }
}